'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  const startTime = Date.now();
  let logId = null;
  
  try {
    console.log('开始执行每日3点重置任务:', new Date());
    
    // 创建任务开始日志
    const startLog = await db.collection('scheduled-task-logs').add({
      taskName: 'dailyReset',
      startTime: new Date(),
      status: 'running',
      collections: ['sunny-users', 'sunny-custom']
    });
    
    logId = startLog.id;

    // 1. 更新 sunny-users 表的 isOnline 字段
    const userUpdateResult = await db.collection('sunny-users')
      .where({
        isOnline: 1
      })
      .update({
        isOnline: 0,
        lastResetTime: new Date()
      });

    console.log('用户表更新完成:', userUpdateResult);

    // 2. 更新 sunny-custom 表的 isregistration 字段
    const customUpdateResult = await db.collection('sunny-custom')
      .where({
        isRegistration: 1
      })
      .update({
        isRegistration: 0,
        lastResetTime: new Date()
      });

    console.log('自定义表更新完成:', customUpdateResult);

    const executionTime = Date.now() - startTime;

    // 3. 更新日志记录为成功
    await db.collection('scheduled-task-logs').doc(logId).update({
      endTime: new Date(),
      executionTime: executionTime,
      status: 'success',
      results: {
        sunnyUsers: {
          updated: userUpdateResult.updated,
          message: `成功更新 ${userUpdateResult.updated} 条用户记录`
        },
        sunnyCustom: {
          updated: customUpdateResult.updated,
          message: `成功更新 ${customUpdateResult.updated} 条自定义记录`
        }
      },
      summary: `任务执行成功，共更新 ${userUpdateResult.updated + customUpdateResult.updated} 条记录，耗时 ${executionTime}ms`
    });

    console.log('每日重置任务执行成功:', {
      更新用户数: userUpdateResult.updated,
      更新自定义记录数: customUpdateResult.updated,
      总耗时: executionTime + 'ms',
      执行时间: new Date()
    });

    return {
      success: true,
      message: '每日重置任务执行成功',
      data: {
        logId: logId,
        usersUpdated: userUpdateResult.updated,
        customUpdated: customUpdateResult.updated,
        totalUpdated: userUpdateResult.updated + customUpdateResult.updated,
        executionTime: executionTime,
        timestamp: new Date()
      }
    };

  } catch (error) {
    console.error('任务执行失败:', error);
    
    const executionTime = Date.now() - startTime;
    
    // 记录错误日志
    if (logId) {
      await db.collection('scheduled-task-logs').doc(logId).update({
        endTime: new Date(),
        executionTime: executionTime,
        status: 'failed',
        error: {
          message: error.message,
          stack: error.stack
        },
        summary: `任务执行失败: ${error.message}`
      });
    } else {
      // 如果连开始日志都没创建成功，则创建新的错误日志
      await db.collection('scheduled-task-logs').add({
        taskName: 'dailyReset',
        startTime: new Date(startTime),
        endTime: new Date(),
        executionTime: executionTime,
        status: 'failed',
        error: {
          message: error.message,
          stack: error.stack
        },
        summary: `任务执行失败: ${error.message}`
      });
    }

    return {
      success: false,
      message: '任务执行失败',
      error: error.message,
      logId: logId
    };
  }
};